import axios from 'axios';

// 设置axios全局默认请求头
axios.defaults.headers.common['User-Agent'] =
  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36';
axios.defaults.headers.common['Referer'] = 'https://www.sporttery.cn/';
axios.defaults.headers.common['Origin'] = 'https://www.sporttery.cn';
axios.defaults.headers.common['Accept'] = 'application/json, text/javascript, */*; q=0.01';
axios.defaults.headers.common['Accept-Language'] = 'zh-CN,zh;q=0.9';
axios.defaults.headers.common['Accept-Encoding'] = 'gzip, deflate, br, zstd';
axios.defaults.headers.common['Priority'] = 'u=1, i';
axios.defaults.headers.common['Sec-Ch-Ua'] = '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"';
axios.defaults.headers.common['Sec-Ch-Ua-Mobile'] = '?0';
axios.defaults.headers.common['Sec-Ch-Ua-Platform'] = '"Windows"';
axios.defaults.headers.common['Sec-Fetch-Dest'] = 'empty';
axios.defaults.headers.common['Sec-Fetch-Mode'] = 'cors';
axios.defaults.headers.common['Sec-Fetch-Site'] = 'same-site';

/**
 * 比赛数据接口
 */
export type MatchData = {
  /** 比赛唯一标识符 */
  matchId: number;
  /** 比赛编号 */
  matchNum: string;
  /** 售卖日期 */
  businessDate: string;
  /** 比赛时间 */
  matchTime: string;
  /** 星期几 */
  weekday: string;
  /** 联赛ID */
  leagueId: string;
  /** 联赛名称 */
  leagueName: string;
  /** 主队信息 */
  homeTeam: {
    /** 主队ID */
    id: string;
    /** 主队简称 */
    name: string;
    /** 主队全称 */
    fullName: string;
    /** 主队排名 */
    rank: string;
  };
  /** 客队信息 */
  awayTeam: {
    /** 客队ID */
    id: string;
    /** 客队简称 */
    name: string;
    /** 客队全称 */
    fullName: string;
    /** 客队排名 */
    rank: string;
  };
  /** 赔率信息 */
  odds: {
    /** 胜平负玩法赔率 */
    had: OddsItem;
    /** 让球胜平负玩法赔率 */
    hhad: OddsItem;
  };
};

/**
 * 赔率项接口
 */
export interface OddsItem {
  /** 客胜赔率 */
  a: string;
  /** 客胜赔率变化方向 (1: 上升, -1: 下降, 0: 无变化) */
  af: string;
  /** 平局赔率 */
  d: string;
  /** 平局赔率变化方向 */
  df: string;
  /** 让球线 */
  goalLine: string;
  /** 让球数值 */
  goalLineValue: string;
  /** 主胜赔率 */
  h: string;
  /** 主胜赔率变化方向 */
  hf: string;
  /** 更新日期 (YYYY-MM-DD) */
  updateDate: string;
  /** 更新时间 (HH:mm:ss) */
  updateTime: string;
}

/**
 * 球队历史比赛数据接口
 */
export interface TeamHistoryMatchesData {
  /** 客队中文简称 */
  awayAbbCnName: string;
  /** 体彩比赛ID */
  gmMatchId: number;
  /** 主队中文简称 */
  homeAbbCnName: string;
  /** 联赛中文简称 */
  leagueAbbCnName: string;
  /** 联赛显示标识 (1: 显示, 0: 不显示) */
  leagueShowFlag: number;
  /** 比赛日期 (YYYY-MM-DD) */
  matchDate: string;
  /** 上半场比分 */
  sectionsNo1: string;
  /** 全场比分 */
  sectionsNo999: string;
  /** 球队比赛结果 ('home': 主队胜, 'away': 客队胜, 'draw': 平局) */
  teamMatchResult: 'home' | 'away' | 'draw';
  /** 统一客队ID */
  uniformAwayTeamId: number;
  /** 统一主队ID */
  uniformHomeTeamId: number;
  /** 统一联赛ID */
  uniformLeagueId: number;
  /** 统一比赛ID */
  uniformMatchId: number;
  /** 外部比赛ID */
  wbsjMatchId: number;
}

export interface OddsHistoryData {
  updateDate: string;
  updateTime: string;
  odds: {
    h: string;
    d: string;
    a: string;
    goalLine?: string;
  };
}

/**
 * 下注方式类型定义
 */
export const BET_TYPES = {
  HAD: {
    key: 'hadList',
    name: '胜平负固定奖金',
    description: '主队胜(H)、平局(D)、客队胜(A)',
    fields: ['h', 'd', 'a'],
  },
  HHAD: {
    key: 'hhadList',
    name: '让球胜平负固定奖金',
    description: '让球胜平负，包含让球数',
    fields: ['h', 'd', 'a', 'goalLine'],
  },
  // CRS: {
  //   key: 'crsList',
  //   name: '比分固定奖金',
  //   description: '准确比分投注, 分别代表 s05s00为5-0, 其他以此类推， s-1sd为平其它，s-1sh为胜其它，s-1sa为负其它',
  //   fields: [
  //     's05s00',
  //     's-1sd',
  //     's-1sh',
  //     's01s00',
  //     's05s02',
  //     's05s01',
  //     's-1sa',
  //     's02s04',
  //     's02s05',
  //     's02s02',
  //     's02s03',
  //     's02s00',
  //     's02s01',
  //     's03s03',
  //     'updateDate',
  //     's03s01',
  //     's03s02',
  //     's03s00',
  //     's00s01',
  //     's00s00',
  //     's00s03',
  //     's00s02',
  //     's00s05',
  //     's00s04',
  //     's04s02',
  //     's04s01',
  //     's04s00',
  //     'updateTime',
  //     's01s02',
  //     's01s01',
  //     's01s04',
  //     's01s03',
  //     's01s05',
  //   ],
  // },
  // TTG: {
  //   key: 'ttgList',
  //   name: '总进球数固定奖金',
  //   description: '全场总进球数0-7+球',
  //   fields: ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7'],
  // },
  // HAFU: {
  //   key: 'hafuList',
  //   name: '半全场胜平负固定奖金',
  //   description: '半场/全场结果组合，分别代表胜胜/胜平/胜负/平胜/平平/平负/负胜/负平/负负',
  //   fields: ['hh', 'hd', 'ha', 'dh', 'dd', 'da', 'ah', 'ad', 'aa'],
  // },
};

export type MatchResultsData = {
  awayTeamAbbName: string;
  awayTeamAllName: string;
  awayTeamId: string;
  homeTeamAbbName: string;
  homeTeamAllName: string;
  homeTeamId: string;
  matchId: number;
  matchMinute: string;
  matchMinuteExtra: string;
  matchPhaseTc: string;
  matchPhaseTcName: string;
  matchStatus: string;
  matchStatusName: string;
  sectionsNo999: string;
  sectionsNos: [
    {
      score: string;
      sectionNo: 1;
    },
    {
      score: string;
      sectionNo: 2;
    },
    {
      score: string;
      sectionNo: 4;
    },
  ];
};

// 1.1 获取所有当前可买比赛数据
export async function getAllMatches() {
  try {
    // API URL和参数
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchCalculatorV1.qry';
    const API_PARAMS = {
      poolCode: 'hhad,had', // 获取胜平负和让球胜平负
      channel: 'c',
    };

    // console.log('正在获取全部比赛数据...');
    const response = await axios.get(API_URL, { params: API_PARAMS });

    // 验证请求是否成功
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const matchInfoList = response.data.value.matchInfoList || [];
    let totalMatches = 0;

    // 计算总比赛数量
    matchInfoList.forEach((dateInfo) => {
      totalMatches += (dateInfo.subMatchList || []).length;
    });

    // console.log(`成功获取比赛数据，共 ${matchInfoList.length} 天, ${totalMatches} 场比赛`);

    return getFormattedMatches(response.data || []);
  } catch (error) {
    console.error('获取全部比赛数据出错:', error.message);
    throw error;
  }
}
// 1.2 获取格式化后的比赛数据
async function getFormattedMatches(allData: any) {
  try {
    const formattedMatches: MatchData[] = [];

    // 遍历每一天的比赛
    allData.value?.matchInfoList?.forEach((dateInfo) => {
      const weekday = dateInfo.weekday;

      // 遍历该天的所有比赛
      (dateInfo.subMatchList || []).forEach((match) => {
        formattedMatches.push({
          businessDate: match.matchDate,
          matchId: match.matchId,
          matchNum: match.matchNumStr,
          matchTime: `${match.matchDate} ${match.matchTime}`,
          weekday: weekday,
          leagueId: match.leagueId,
          leagueName: match.leagueAbbName,
          homeTeam: {
            id: match.homeTeamId,
            name: match.homeTeamAbbName,
            fullName: match.homeTeamAllName,
            rank: match.homeRank,
          },
          awayTeam: {
            id: match.awayTeamId,
            name: match.awayTeamAbbName,
            fullName: match.awayTeamAllName,
            rank: match.awayRank,
          },
          odds: {
            had: match.had || {}, // 胜平负赔率
            hhad: match.hhad || {}, // 让球胜平负赔率
          },
        });
      });
    });

    return formattedMatches;
  } catch (error) {
    console.error('获取格式化比赛数据出错:', error.message);
    throw error;
  }
}

// 2 获取球队历史比赛数据
export async function getTeamHistoryMatches(params: { gmTeamId: string; termLimits: number; homeAwayFlag?: 'home' | 'away' }) {
  try {
    // 发送API请求
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/team/getMatchResultV1.qry';
    const response = await axios.get(url, { params });

    // 验证响应数据
    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return (response.data?.value?.matchList as TeamHistoryMatchesData[]) || [];
  } catch (error) {
    console.error('获取球队历史比赛数据出错:', error.message);
    throw error;
  }
}

// 3.1 获取球队积分榜数据
export async function getTeamRanking(params: { gmMatchId: number }) {
  try {
    const url = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchTablesV2.qry';
    const response = await axios.get(url, { params });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    return formatTablesData(response.data.value);
  } catch (error) {
    console.error('获取积分榜数据出错:', error.message);
    throw error;
  }
}
// 3.2 格式化积分榜数据，提取关键信息
async function formatTablesData(tablesData) {
  if (!tablesData) return null;

  const formatTeamData = (teamData) => {
    if (!teamData) return null;

    return {
      总积分榜: {
        球队: teamData.total?.teamShortName || '',
        排名: teamData.total?.ranking || '',
        积分: teamData.total?.points || '',
        场次: teamData.total?.totalLegCnt || 0,
        胜: teamData.total?.winGoalMatchCnt || 0,
        平: teamData.total?.drawMatchCnt || 0,
        负: (teamData.total?.totalLegCnt || 0) - (teamData.total?.winGoalMatchCnt || 0) - (teamData.total?.drawMatchCnt || 0),
        进球: teamData.total?.goalCnt || 0,
        失球: teamData.total?.lossGoalCnt || 0,
        净胜球: teamData.total?.netGoal || 0,
        胜率: teamData.total?.winProbability || '0%',
      },
      主场积分榜: {
        球队: teamData.home?.teamShortName || '',
        排名: teamData.home?.ranking || '',
        积分: teamData.home?.points || '',
        场次: teamData.home?.totalLegCnt || 0,
        胜: teamData.home?.winGoalMatchCnt || 0,
        平: teamData.home?.drawMatchCnt || 0,
        负: (teamData.home?.totalLegCnt || 0) - (teamData.home?.winGoalMatchCnt || 0) - (teamData.home?.drawMatchCnt || 0),
        进球: teamData.home?.goalCnt || 0,
        失球: teamData.home?.lossGoalCnt || 0,
        净胜球: teamData.home?.netGoal || 0,
        胜率: teamData.home?.winProbability || '0%',
      },
      客场积分榜: {
        球队: teamData.away?.teamShortName || '',
        排名: teamData.away?.ranking || '',
        积分: teamData.away?.points || '',
        场次: teamData.away?.totalLegCnt || 0,
        胜: teamData.away?.winGoalMatchCnt || 0,
        平: teamData.away?.drawMatchCnt || 0,
        负: (teamData.away?.totalLegCnt || 0) - (teamData.away?.winGoalMatchCnt || 0) - (teamData.away?.drawMatchCnt || 0),
        进球: teamData.away?.goalCnt || 0,
        失球: teamData.away?.lossGoalCnt || 0,
        净胜球: teamData.away?.netGoal || 0,
        胜率: teamData.away?.winProbability || '0%',
      },
    };
  };

  return {
    tournamentId: tablesData.tournamentId,
    联赛信息: {
      联赛: tablesData.leagueShortName || '',
      赛季: tablesData.seasonName || '',
      阶段: tablesData.homeTables?.total?.phaseName || '',
    },
    主队数据: formatTeamData(tablesData.homeTables),
    客队数据: formatTeamData(tablesData.awayTables),
  };
}

// 4.1 获取比赛赔率变化 https://www.sporttery.cn/jc/zqdz/index.html?showType=3&mid=2033598
export async function getOddsHistory(matchId: number) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry';
    const API_PARAMS = {
      clientCode: '3001',
      matchId: matchId,
    };

    console.log(`正在获取比赛 ${matchId} 的赔率变化数据...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    const oddsHistory = response.data.value.oddsHistory;

    // 格式化赔率历史数据
    const formattedOdds = {};

    // 遍历每种下注类型
    Object.entries(BET_TYPES).forEach(([typeKey, typeInfo]) => {
      const historyData = oddsHistory[typeInfo.key];
      if (historyData && historyData.length > 0) {
        formattedOdds[typeKey] = {
          type: typeInfo.name,
          description: typeInfo.description,
          history: historyData.map((record) => {
            const formattedRecord = {
              updateDate: record.updateDate,
              updateTime: record.updateTime,
              odds: {},
            };

            // 提取对应字段的赔率和变化标志
            typeInfo.fields.forEach((field) => {
              if (record[field] !== undefined) {
                formattedRecord.odds[field] = record[field];
                // 获取变化标志（字段名+f）
              }
            });

            return formattedRecord;
          }),
        };
      }
    });

    console.log(`成功获取比赛 ${matchId} 的赔率变化数据`);

    return formattedOdds as Record<keyof typeof BET_TYPES, { type: string; description: string; history: OddsHistoryData[] }>;
  } catch (error) {
    console.error(`获取比赛 ${matchId} 赔率变化数据出错:`, error.message);
    throw error;
  }
}

// 5 获取比赛开奖结果
/**
 * 获取比赛开奖结果
 * @param {string} matchId - 比赛ID
 * @returns {Promise<Object>} 返回开奖结果数据
 */
export async function getMatchResults(matchId: number, homeTeamId: string) {
  try {
    const API_URL = 'https://webapi.sporttery.cn/gateway/uniform/fb/getMatchScoreV1.qry';
    const API_PARAMS = {
      matchId: matchId,
    };

    console.log(`正在获取比赛 ${matchId} 的开奖结果...`);
    const response = await axios.get(API_URL, { params: API_PARAMS });

    if (!response.data.success) {
      throw new Error(`API请求失败: ${response.data.errorMessage}`);
    }

    // 如果没有半场比分
    const hasHadScore = response.data?.value?.sectionsNos?.some((item) => item.sectionNo === 1);
    if (!hasHadScore) {
      const homeHistory = await getTeamHistoryMatches({ gmTeamId: homeTeamId, termLimits: 1, homeAwayFlag: 'home' });
      if (homeHistory?.[0] && homeHistory[0].gmMatchId === matchId) {
        response.data?.value?.sectionsNos?.push({
          score: homeHistory[0].sectionsNo1,
          sectionNo: 1,
        });
      }
    }

    return response.data?.value as MatchResultsData;
  } catch (error) {
    console.error(`获取比赛 ${matchId} 开奖结果出错:`, error.message);
    throw error;
  }
}
